var url = {
	http : "http://",
	https : "https://",
	ws: "ws://",
	host : "localhost:8080"
}

url.login = url.http+url.host+"/auth.do";
url.osclogin = url.http+"www.oschina.net/action/api/login_validate"
url.authosc = url.http+url.host+"/authosc.do";

function _post(url,data,callback){
	$.ajax({
		url: url,
		type: 'POST',
		data: data,
		dataType:"JSON",
		success: function(data) {
			callback(data);
		},
		error:function (msg){
			callback({result:"CONNECTION_FAIL"});
		}
	});
}

function _postxml(url,data,callback){
	$.ajax({
		url: url,
		type: 'POST',
		data: data,
		success: function(data) {
			callback(data);
		},
		error:function (msg){
			callback({result:"CONNECTION_FAIL"});
		}
	});
}

function _get(url,data,callback){
	if (url.indexOf("?") < 0) {
		url += "?";
	}
	for (var d in data) {
		url += "&" + d + "=" + data[d];
	}
	$.ajax({
		url: url.replace("?&", "?"),
		type: 'GET',
		//dataType:'html/text',
		dataType:"JSON",
		success: function(data) {
			callback(eval('(' + data + ')'));
		},
		error:function (XMLHttpRequest, textStatus, errorThrown){
			callback({result:"CONNECTION_FAIL"});
		}
	});
}

var api = (function(){
	return {
		login : function(username,password,callback){
			var data={
				username:username,
				password:password
			}
			_post(url.login,data,callback );
		},
		loginosc : function(username, password, callback) {
			var data = {
				"username": username,
				"pwd": password,
				"keep_login": 1
			};
			_postxml(url.osclogin, data, function(xml){
				var oscu = api.oscuserparse(xml);
				oscu.username = username;
				console.info(oscu);
				_post(url.authosc,oscu,callback );
			});
		},
		

		oscuserparse : function(xml) {
			var u = $(xml).find('user');
			return {
				uid: $(u).children('uid').text(),
				name: $(u).children('name').text(),
				location: $(u).children('location').text(),
				followers: $(u).children('followers').text(),
				fans: $(u).children('fans').text(),
				score: $(u).children('score').text(),
				portrait: $(u).children('portrait').text()
			};
		}
	};
})();


var util = (function(){
	return {
		jsonToString:function(obj){
			var THIS = this;    
	        switch(typeof(obj)){   
	            case 'string':   
	                return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';   
	            case 'array':   
	                return '[' + obj.map(THIS.jsonToString).join(',') + ']';   
	            case 'object':   
	                 if(obj instanceof Array){   
	                    var strArr = [];   
	                    var len = obj.length;   
	                    for(var i=0; i<len; i++){   
	                        strArr.push(THIS.jsonToString(obj[i]));   
	                    }   
	                    return '[' + strArr.join(',') + ']';   
	                }else if(obj==null){   
	                    return 'null';   
	  
	                }else{   
	                    var string = [];   
	                    for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));   
	                    return '{' + string.join(',') + '}';   
	                }   
	            case 'number':   
	                return obj;   
	            case false:   
	                return obj;   
	        }
		},

		getQuery:function(name){
			var vars = [], hash;
		    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		    for(var i = 0; i < hashes.length; i++)
		    {
		      hash = hashes[i].split('=');
		      vars.push(hash[0]);
		      vars[hash[0]] = hash[1];
		    }
		    return vars[name];
		},
		
		isNull: function(o) {
			return (o == null || typeof(o) == 'undefined');
		},
		
		isDate: function(o) {
			return Object.prototype.toString.call(o) === "[object Date]";
		},
		
		date2String : function(date,format){
			if (!util.isDate(date) || util.isNull(format)) {
				return "";
			}
			var o = {
				"M+": date.getMonth() + 1, // month
				"d+": date.getDate(), // day
				"H+": date.getHours(), // hour
				"m+": date.getMinutes(), // minute
				"s+": date.getSeconds(), // second
				"q+": Math.floor((date.getMonth() + 3) / 3), // quarter
				"S": date.getMilliseconds()
				// millisecond
			}

			if (/(y+)/.test(format)) {
				format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
			}

			for (var k in o) {
				if (new RegExp("(" + k + ")").test(format)) {
					format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
				}
			}
			return format;
		}
	};
})();